<?php

class Joob_Plugins_Manager {
	
	private static $instance;
	
	private $plugins;
	
	private function __construct()	{
		$this->plugins = array();
	}
	
	public static function getInstance()	{
		if (self::$instance == null)	{
			self::$instance = new Joob_Plugins_Manager();
		}
		return self::$instance;
	}
	
	/**
	 * Register a plugin and load it if requested
	 * @param Joob_Plugins_Interface $plugin the plugin to be registered
	 */
	public function register($plugin, $loaded = true)	{
		$this->plugins[] = $plugin;
		if (!$plugin->isLoaded() && $loaded)	{
			$plugin->onLoad();
		}
	}
	
	/**
	 * Unregister a plugin and unload it
	 * @param Joob_Plugins_Interface $plugin the plugin to be unregistered
	 */
	public function unregister($plugin)	{
		$index = $this->getPluginIndex($plugin);
		if ($index !== false)	{
			$plugin->onUnload();
			unset($this->plugins[$index]);
			//reindex the array
			array_values($this->plugins);
		}
	}
	
	/**
	 * Get the plugin index
	 * @param Joob_Plugins_Interface $plugin
	 * @return the plugin index or false if not found.
	 * Please note the false is similar to zero or null with == operand
	 */
	public function getPluginIndex($plugin)	{
		return array_search($plugin, $this->plugins);
	}
	
	/**
	 * Get all plugins
	 */
	public function getPlugins()	{
		return $this->plugins;
	}
}

?>